<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="订单号" prop="orderNo">
              <j-select-finished-order-modal
                v-model="selectedOrderIds"
                placeholder="请选择已完成生产的订单"
                @change="handleOrderSelected"
              >
              </j-select-finished-order-modal>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="入库日期" prop="inboundDate">
              <a-date-picker
                v-model="model.inboundDate"
                style="width: 100%"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              ></a-date-picker>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" prop="remark">
              <a-textarea v-model="model.remark" placeholder="请输入备注" :rows="3"></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <!-- 入库明细表格 -->
      <a-divider>入库明细</a-divider>
      <div style="margin-bottom: 16px">
        <a-button @click="addDetail" type="primary" icon="plus" size="small">添加明细</a-button>
        <a-button
          @click="removeDetail"
          type="danger"
          icon="minus"
          size="small"
          style="margin-left: 8px"
          :disabled="selectedDetailKeys.length === 0"
          >删除明细</a-button
        >
      </div>

      <a-table
        :columns="detailColumns"
        :dataSource="detailList"
        :pagination="false"
        size="middle"
        bordered
        rowKey="key"
        :rowSelection="detailRowSelection"
      >
        <template slot="windowSeries" slot-scope="text, record">
          <a-input v-model="record.windowSeries" placeholder="请输入门窗系列"></a-input>
        </template>
        <template slot="windowNo" slot-scope="text, record">
          <a-input v-model="record.windowNo" placeholder="请输入门窗窗号"></a-input>
        </template>
        <template slot="windowColor" slot-scope="text, record">
          <a-input v-model="record.windowColor" placeholder="请输入门窗颜色"></a-input>
        </template>
        <template slot="plannedQuantity" slot-scope="text, record">
          <a-input-number v-model="record.plannedQuantity" :min="1" style="width: 100%"></a-input-number>
        </template>
        <template slot="actualQuantity" slot-scope="text, record">
          <a-input-number
            v-model="record.actualQuantity"
            :min="0"
            placeholder="请输入实际数量"
            style="width: 100%"
          ></a-input-number>
        </template>
        <template slot="warehouseId" slot-scope="text, record">
          <a-select
            v-model="record.warehouseId"
            placeholder="请选择仓库"
            style="width: 100%"
            showSearch
            optionFilterProp="children"
            allowClear
            @change="(value) => handleDetailWarehouseChange(record, value)"
          >
            <a-select-option v-for="warehouse in warehouseList" :key="warehouse.id" :value="warehouse.id">
              {{ warehouse.warehouseName }}
              <span v-if="warehouse.warehouseType === '7'" style="color: #52c41a">(推荐)</span>
            </a-select-option>
            <a-select-option v-if="warehouseList.length === 0" disabled>正在加载仓库数据...</a-select-option>
          </a-select>
        </template>
        <template slot="locationId" slot-scope="text, record">
          <j-select-warehouse-location
            v-model="record.locationId"
            :warehouseId="record.warehouseId"
            placeholder="请选择库位"
          ></j-select-warehouse-location>
        </template>
        <template slot="productionBatchNo" slot-scope="text, record">
          <a-input v-model="record.productionBatchNo" placeholder="请输入生产批次号"></a-input>
        </template>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import { createInbound, getInboundDetail, updateInbound } from '@/api/wms/finishedGoodsInbound'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
import JSelectFinishedOrderModal from '@/components/jeecgbiz/JSelectFinishedOrderModal'

export default {
  name: 'InboundCreateModal',
  components: {
    JSelectWarehouse,
    JSelectWarehouseLocation,
    JSelectFinishedOrderModal,
  },
  data() {
    return {
      title: '创建入库单',
      visible: false,
      confirmLoading: false,
      model: {
        inboundDate: new Date().toISOString().split('T')[0],
      },
      selectedOrderIds: [],
      detailList: [],
      selectedDetailKeys: [],
      detailKeyIndex: 1,
      warehouseList: [],
      warehouseNameMap: {},
      editMode: false,
      editRecord: null,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 },
      },
      validatorRules: {
        inboundDate: [{ required: true, message: '请选择入库日期!', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择仓库!', trigger: 'change' }],
      },
      detailColumns: [
        {
          title: '门窗系列',
          dataIndex: 'windowSeries',
          width: 120,
          scopedSlots: { customRender: 'windowSeries' },
        },
        {
          title: '门窗窗号',
          dataIndex: 'windowNo',
          width: 120,
          scopedSlots: { customRender: 'windowNo' },
        },
        {
          title: '门窗颜色',
          dataIndex: 'windowColor',
          width: 100,
          scopedSlots: { customRender: 'windowColor' },
        },
        {
          title: '计划数量',
          dataIndex: 'plannedQuantity',
          width: 100,
          scopedSlots: { customRender: 'plannedQuantity' },
        },
        {
          title: '实际数量',
          dataIndex: 'actualQuantity',
          width: 100,
          scopedSlots: { customRender: 'actualQuantity' },
        },
        {
          title: '仓库',
          dataIndex: 'warehouseId',
          width: 120,
          scopedSlots: { customRender: 'warehouseId' },
        },
        {
          title: '库位',
          dataIndex: 'locationId',
          width: 150,
          scopedSlots: { customRender: 'locationId' },
        },
        {
          title: '生产批次号',
          dataIndex: 'productionBatchNo',
          width: 120,
          scopedSlots: { customRender: 'productionBatchNo' },
        },
      ],
      detailRowSelection: {
        selectedRowKeys: [],
        onChange: (selectedRowKeys) => {
          this.selectedDetailKeys = selectedRowKeys
        },
      },
    }
  },
  methods: {
    show(record) {
      this.visible = true
      this.resetForm()
      // 加载仓库列表
      this.loadWarehouseList()
      if (record) {
        this.title = '编辑入库单'
        this.editMode = true
        this.editRecord = record
        this.loadEditData(record.id)
      } else {
        this.title = '创建入库单'
        this.editMode = false
        this.editRecord = null
        this.model = {
          inboundDate: new Date().toISOString().split('T')[0]
        }
        this.detailList = []
        this.selectedOrderIds = []
      }
    },
    handleOk() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.detailList.length === 0) {
            this.$message.error('请添加入库明细')
            return
          }

          this.confirmLoading = true

          // 获取第一个明细的仓库ID作为主仓库ID（用于满足后端验证）
          const firstDetailWarehouseId = this.detailList.length > 0 ? this.detailList[0].warehouseId : ''
          const formData = {
            ...this.model,
            warehouseId: firstDetailWarehouseId,
            detailList: this.detailList.map((item) => ({
              id: item.id || undefined,
              orderDetailId: item.orderDetailId || '',
              windowSeries: item.windowSeries,
              windowNo: item.windowNo,
              windowColor: item.windowColor,
              plannedQuantity: item.plannedQuantity,
              actualQuantity: item.actualQuantity,
              warehouseId: item.warehouseId,
              locationId: item.locationId,
              productionBatchNo: item.productionBatchNo,
              qualityStatus: item.qualityStatus || 0,
              qualityInspector: item.qualityInspector
            }))
          }

          const apiCall = this.editMode ? updateInbound(formData) : createInbound(formData)
          const successMessage = this.editMode ? '入库单更新成功' : '入库单创建成功'
          const errorMessage = this.editMode ? '更新失败' : '创建失败'

          apiCall
            .then((res) => {
              if (res.success) {
                this.$message.success(successMessage)
                this.handleCancel()
                this.$emit('ok')
              } else {
                this.$message.error(res.message || errorMessage)
              }
              this.confirmLoading = false
            })
            .catch((err) => {
              this.$message.error(errorMessage + '：' + err.message)
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.model = {
        inboundDate: new Date().toISOString().split('T')[0],
      }
      this.detailList = []
      this.selectedDetailKeys = []
      this.selectedOrderIds = []
      this.$refs.form.resetFields()
    },
    handleOrderSelected(orders) {
      if (orders && orders.length > 0) {
        // 取第一个订单作为主订单信息
        const mainOrder = orders[0]
        this.model.orderId = mainOrder.id
        this.model.orderNo = mainOrder.orderNo
        this.model.customerName = mainOrder.customerName
        this.model.projectName = mainOrder.projectName

        // 自动获取订单明细并生成入库明细
        this.fetchOrderDetailsAndGenerateInbound(mainOrder.id)
      }
    },
    async fetchOrderDetailsAndGenerateInbound(orderId) {
      try {
        this.confirmLoading = true

        // 确保仓库列表已加载
        if (this.warehouseList.length === 0) {
          await this.loadWarehouseList()
        }

        // 调用后端API获取订单明细
        const response = await this.$http.get(`/oms/productSalesOrder/detail/getDetailsByOrderId?orderId=${orderId}`)

        if (response.success && response.result) {
          const orderDetails = response.result

          // 清空现有明细
          this.detailList = []

          // 根据订单明细生成入库明细
          for (let i = 0; i < orderDetails.length; i++) {
            const detail = orderDetails[i]

            // 自动分配库位
            const locationInfo = await this.allocateWarehouseLocation(detail)

            const detailRecord = {
              key: this.detailKeyIndex++,
              orderDetailId: detail.id,
              windowSeries: detail.windowSeries || detail.productSeries || '',
              windowNo: detail.windowNo || detail.productCode || '',
              windowColor: detail.windowColor || detail.color || '',
              plannedQuantity: detail.quantity || 1,
              actualQuantity: detail.quantity || 1,
              warehouseId: locationInfo.warehouseId || '',
              warehouseName: locationInfo.warehouseName || '',
              locationId: locationInfo.locationId || '',
              locationName: locationInfo.locationName || '',
              productionBatchNo: this.getCurrentDate(),
              qualityStatus: 0,
              qualityInspector: '',
            }

            console.log('添加明细记录:', detailRecord)
            this.detailList.push(detailRecord)

            // 更新仓库名称映射
            if (locationInfo.warehouseId && locationInfo.warehouseName) {
              this.warehouseNameMap[locationInfo.warehouseId] = locationInfo.warehouseName
            }
          }

          this.$message.success(`成功加载 ${orderDetails.length} 条订单明细`)
        } else {
          this.$message.error('获取订单明细失败：' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取订单明细失败:', error)
        this.$message.error('获取订单明细失败：' + error.message)
      } finally {
        this.confirmLoading = false
      }
    },

    async allocateWarehouseLocation(orderDetail) {
      try {
        const params = {
          orderNo: this.model.orderNo,
          finishedGoods: [
            {
              orderDetailId: orderDetail.id,
              windowNo: orderDetail.windowNo || orderDetail.productCode || '',
              windowSeries: orderDetail.windowSeries || orderDetail.productSeries || '',
            },
          ],
        }

        const response = await this.$http.post('/wms/location/recommendLocationsByFinishedGoods', params)

        if (response.success && response.result && response.result.length > 0) {
          const result = response.result[0]
          if (result.success) {
            console.log('库位分配成功:', result)
            return {
              warehouseId: result.warehouseId,
              warehouseName: result.warehouseName,
              locationId: result.locationId,
              locationName: result.locationName,
            }
          } else {
            console.warn('库位分配失败:', result.error)
            this.$message.warning(`窗号${orderDetail.windowNo}库位分配失败: ${result.error}`)
          }
        }
      } catch (error) {
        console.error('分配库位失败:', error)
        this.$message.error('分配库位失败: ' + error.message)
      }

      // 如果分配失败，返回空值
      return { warehouseId: '', warehouseName: '', locationId: '', locationName: '' }
    },

    generateInboundDetails(orders) {
      // 清空现有明细
      this.detailList = []

      // 根据订单信息生成入库明细（这里可以调用后端API获取订单明细）
      orders.forEach((order, index) => {
        this.detailList.push({
          key: this.detailKeyIndex++,
          orderDetailId: order.id,
          windowSeries: `系列${index + 1}`,
          windowNo: `窗号${index + 1}`,
          windowColor: '白色',
          plannedQuantity: 1,
          actualQuantity: 1,
          locationId: '',
          productionBatchNo: '',
          qualityStatus: 0,
          qualityInspector: '',
        })
      })
    },
    addDetail() {
      this.detailList.push({
        key: this.detailKeyIndex++,
        windowSeries: '',
        windowNo: '',
        windowColor: '',
        plannedQuantity: 1,
        actualQuantity: 1,
        locationId: '',
        productionBatchNo: '',
        qualityStatus: 0,
        qualityInspector: '',
      })
    },
    removeDetail() {
      this.detailList = this.detailList.filter((item) => !this.selectedDetailKeys.includes(item.key))
      this.selectedDetailKeys = []
    },
    handleWarehouseChange(value) {
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.form.validateField('warehouseId')
      })
    },

    // 获取当前日期，格式为YYYYMMDD
    getCurrentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      return `${year}${month}${day}`
    },

    // 加载仓库列表
    async loadWarehouseList() {
      try {
        const response = await this.$http.get('/wms/warehouse/list')
        if (response.success && response.result && response.result.records) {
          this.warehouseList = response.result.records
          // 创建仓库名称映射
          this.warehouseNameMap = {}
          this.warehouseList.forEach((warehouse) => {
            this.warehouseNameMap[warehouse.id] = warehouse.warehouseName
          })
        }
      } catch (error) {
        console.error('加载仓库列表失败:', error)
        this.$message.error('加载仓库列表失败')
      }
    },

    // 处理明细行仓库变更
    handleDetailWarehouseChange(record, warehouseId) {
      // 清空库位选择
      record.locationId = ''
      record.locationName = ''

      // 更新仓库名称
      if (warehouseId && this.warehouseNameMap[warehouseId]) {
        record.warehouseName = this.warehouseNameMap[warehouseId]
      }

      // 强制更新视图
      this.$forceUpdate()
    },

    // 加载编辑数据
    async loadEditData(inboundId) {
      try {
        this.confirmLoading = true
        const response = await getInboundDetail(inboundId)

        if (response.success && response.result) {
          const data = response.result

          // 设置主表单数据
          this.model = {
            id: data.id,
            inboundNo: data.inboundNo,
            orderId: data.orderId,
            orderNo: data.orderNo,
            customerName: data.customerName,
            projectName: data.projectName,
            warehouseId: data.warehouseId,
            inboundDate: data.inboundDate,
            remark: data.remark || ''
          }
          
          // 设置选中的订单ID
          if (data.orderId) {
            this.selectedOrderIds = [data.orderId]
          }

          // 设置明细数据
          if (data.detailList && data.detailList.length > 0) {
            this.detailList = data.detailList.map((detail, index) => ({
              key: this.detailKeyIndex++,
              id: detail.id,
              orderDetailId: detail.orderDetailId,
              windowSeries: detail.windowSeries || '',
              windowNo: detail.windowNo || '',
              windowColor: detail.windowColor || '',
              plannedQuantity: detail.plannedQuantity || 0,
              actualQuantity: detail.actualQuantity || 0,
              warehouseId: detail.warehouseId || data.warehouseId,
              warehouseName: detail.warehouseName || '',
              locationId: detail.locationId || '',
              locationName: detail.locationName || '',
              productionBatchNo: detail.productionBatchNo || '',
              qualityStatus: detail.qualityStatus || 0,
              qualityInspector: detail.qualityInspector || ''
            }))
          }
          this.$message.success('编辑数据加载成功')
        } else {
          this.$message.error('加载编辑数据失败：' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('加载编辑数据失败:', error)
        this.$message.error('加载编辑数据失败：' + error.message)
      } finally {
        this.confirmLoading = false
      }
    },

    // 重置表单
    resetForm() {
      this.model = {
        inboundDate: new Date().toISOString().split('T')[0],
        warehouseId: '',
        remark: ''
      }
      this.detailList = []
      this.selectedDetailKeys = []
      this.editMode = false
      this.editRecord = null
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
  },
}
</script>
